package com.lantosec.hmrp.core.util;

import org.apache.commons.codec.binary.Base64;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class FileUtils {
    public static final String FILEACTIVITI = "uploadFiles/activitiFile/";

    public static File getFile(String filePath) {
        return new File(filePath);
    }

    public static File getFile(String path, String name) {
        return new File(path, name);
    }

    public static String getFileName(String name) {
        return getFileName(getFile(name));
    }

    public static String getFileName(String name, boolean suffix) {
        return getFileName(getFile(name), suffix);
    }

    public static String getFileName(File f) {
        return getFileName(f, false);
    }

    public static String getFileName(File f, boolean suffix) {
        if (!f.exists()) {
            throw new NullPointerException();
        }
        String name = f.getName();
        if (!suffix) {
            if (name.indexOf(".") > 0) {
                name = name.substring(0, name.indexOf("."));
            }
        }
        return name;
    }

    public static String getFileSuffix(String fileName) {
        if (fileName.indexOf(".") > 0) {
            return fileName.substring(fileName.indexOf("."));
        } else {
            return "";
        }
    }

    public static String getFileSuffix(File f) {
        return getFileSuffix(getFileName(f, true));
    }

    public static Boolean zip(String inputFileName, String zipFileName) throws Exception {
        zip(zipFileName, new File(inputFileName));
        return true;
    }

    private static void zip(String zipFileName, File inputFile) throws Exception {
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));
        zip(out, inputFile, "");
        out.flush();
        out.close();
    }

    private static void zip(ZipOutputStream out, File f, String base) throws Exception {
        if (f.isDirectory()) {
            File[] fl = f.listFiles();
            out.putNextEntry(new ZipEntry(base + "/"));
            base = base.length() == 0 ? "" : base + "/";
            for (int i = 0; i < fl.length; i++) {
                zip(out, fl[i], base + fl[i].getName());
            }
        } else {
            out.putNextEntry(new ZipEntry(base));
            FileInputStream in = new FileInputStream(f);
            int b;
            while ((b = in.read()) != -1) {
                out.write(b);
            }
            in.close();
        }
    }

    public static String getImageStr(String imgSrcPath) {
        InputStream in = null;
        byte[] data = null;
        // 读取图片字节数组
        try {
            in = new FileInputStream(imgSrcPath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 对字节数组Base64编码
        return Base64.encodeBase64String(data);// 返回Base64编码过的字节数组字符串
    }

    public static String readFileAllContent(String fileP) {
        StringBuffer fileContent = new StringBuffer();
        try {
            String encoding = "utf-8";
            File file = new File(FileUtils.getProjectpath() + fileP);//文件路径
            if (file.isFile() && file.exists()) { 		// 判断文件是否存在
                InputStreamReader read = new InputStreamReader(
                        new FileInputStream(file), encoding);	// 考虑到编码格式
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt = null;
                while ((lineTxt = bufferedReader.readLine()) != null) {
                    fileContent.append(lineTxt);
                    fileContent.append("\n");
                }
                read.close();
            }else{
                System.out.println("找不到指定的文件,查看此路径是否正确:"+fileP);
            }
        } catch (Exception e) {
            System.out.println("读取文件内容出错");
        }
        return fileContent.toString();
    }

    public static byte[] toByteArray2(String filePath) throws IOException {
        File f = new File(filePath);
        if (!f.exists()) {
            throw new FileNotFoundException(filePath);
        }
        FileChannel channel = null;
        FileInputStream fs = null;
        try {
            fs = new FileInputStream(f);
            channel = fs.getChannel();
            ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size());
            while ((channel.read(byteBuffer)) > 0) {
                // do nothing
                // System.out.println("reading");
            }
            return byteBuffer.array();
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        } finally {
            try {
                channel.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                fs.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static String copyFile(InputStream in, String dir, String realName)
            throws IOException {
        File file = mkdirs(dir,realName);
        org.apache.commons.io.FileUtils.copyInputStreamToFile(in, file);
        in.close();
        return realName;
    }

    public static String fileUpload(MultipartFile file, String filePath, String fileName){
        String extName = ""; // 扩展名格式：
        try {
            if (file.getOriginalFilename().lastIndexOf(".") >= 0){
                extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            }
            copyFile(file.getInputStream(), filePath, fileName+extName).replaceAll("-", "");
        } catch (IOException e) {
            System.out.println(e);
        }
        return fileName+extName;
    }

    public static void fileDownload(final HttpServletResponse response, String filePath, String fileName) throws Exception{
        byte[] data = FileUtils.toByteArray2(filePath);
        fileName = URLEncoder.encode(fileName, "UTF-8");
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream;charset=UTF-8");
        OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        outputStream.write(data);
        outputStream.flush();
        outputStream.close();
        response.flushBuffer();
    }

    public static String getProjectpath(){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        return request.getServletContext().getRealPath("/").replaceAll("%20", " ").replaceAll("file:/", "").trim();
    }

    public static File mkdirs(String dir, String realName) throws IOException{
        File file = new File(dir, realName);
        if (!file.exists()) {
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            file.createNewFile();
        }
        return file;
    }

    public static boolean creatFolder(String folderPath) throws IOException, NullPointerException, SecurityException {
        File filePath = new File(folderPath);
        if (!filePath.exists()) {
            boolean isCreat = filePath.mkdir();
            if (!isCreat) {
                isCreat = filePath.mkdirs();
            }
            filePath = null;
            return isCreat;
        } else {
            filePath = null;
            return true;
        }
    }

    public static boolean isExists(String path) {
        File f = getFile(path);
        return f.exists();
    }

    public static File creatFile(String filePath, String fileName)
            throws IOException, NullPointerException, SecurityException {
        File file = new File(filePath, fileName);
        if (!file.exists()) {
            if (file.createNewFile()) {
                return file;
            } else {
                return null;
            }
        } else {
            return file;
        }
    }

    public static boolean deleteFolder(String folderPath) throws NullPointerException, SecurityException {
        File delFolder = new File(folderPath);
        boolean isDel = delFolder.delete();
        delFolder = null;
        return isDel;
    }

    public static void deleteFolderAllFiles(String folderPath) throws NullPointerException, SecurityException {
        File delFolder = new File(folderPath);
        File[] files = delFolder.listFiles();
        if (files != null && files.length > 0) {
            for (File file : files) {
                if (!file.isDirectory()) {
                    file.delete();
                }
                file = null;
            }
        }
        files = null;
        delFolder = null;
    }

    public static void fileWriter(File file, String content) throws IOException, FileNotFoundException {
        fileWriter(file, content, false, false);
    }

    public static void fileWriter(File file, String content, boolean append) throws IOException, FileNotFoundException {
        fileWriter(file, content, append, false);
    }

    public static void fileWriter(File file, String content, boolean append, boolean newline)
            throws IOException, FileNotFoundException {
        FileWriter writer = new FileWriter(file, append);
        if (newline) {
            String newlineStr = System.getProperty("line.separator");
            if (!(content.substring(content.length() - 2).equals(newlineStr))
                    || !(content.substring(content.length() - 1).equals("\n"))) {
                content += newlineStr;
            }
        }
        writer.write(content);
        writer.close();
        writer = null;
    }

    public static BufferedReader fileReader(File file) throws FileNotFoundException {
        BufferedReader reader = new BufferedReader(new FileReader(file));
        return reader;
    }

    public static String fileRead(File file) throws IOException {
        String content = "";
        BufferedReader reader = new BufferedReader(new FileReader(file));
        String line = "";
        while ((line = reader.readLine()) != null) {
            content += line + System.getProperty("line.separator");
        }
        reader.close();
        reader = null;
        return content;
    }

    /**
     * 获取文件大小 返回 KB 保留3位小数  没有文件时返回0
     *
     * @param filepath 文件完整路径，包括文件名
     * @return
     */
    public static Double getFilesize(String filepath) {
        File backupath = new File(filepath);
        return Double.valueOf(backupath.length()) / 1000.000;
    }
}
